package com.imyyq.sample.db

import android.app.Application
import com.imyyq.mvvm.utils.LogUtil
import android.view.View
import androidx.databinding.ObservableArrayList
import androidx.lifecycle.*
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.imyyq.mvvm.base.BaseModel
import com.imyyq.mvvm.base.BaseViewModel
import com.imyyq.mvvm.room.RoomUtil
import com.imyyq.sample.BR
import com.imyyq.sample.R
import com.imyyq.sample.data.source.local.AppDatabase
import com.imyyq.sample.entity.User
import com.imyyq.sample.rv.RvItemViewModel
import com.imyyq.sample.rv.RvItemViewModelDB
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import me.tatarka.bindingcollectionadapter2.itembindings.OnItemBindClass
import me.tatarka.bindingcollectionadapter2.map
import kotlin.concurrent.thread

class DBViewModel(app: Application) : BaseViewModel<BaseModel>(app) {
    val observableList = ObservableArrayList<Any>()
    lateinit var owner: LifecycleOwner
    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        this.owner = owner
        database.getUserDao().getAllUser().observe(owner, Observer {
            it.forEach {m ->
                observableList.add(RvItemViewModelDB(this,m))
            }
        })
        database.getUserDao().getAllUser().removeObservers(owner)
    }


    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
    }
    // room 版本升级
    private val migration: Migration = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            LogUtil.i("DBViewModel", "commonLog - migrate: ")
            database.execSQL("alter table user add column `version2` TEXT")
        }
    }

    private val database = RoomUtil.getDB(AppDatabase::class.java, migrations = arrayOf(migration))

    //将livedata从LiveData<List<User>>转换成了LiveData<String>
//    val userLiveData: LiveData<String> = Transformations.map(
//        database.getUserDao().getAllUser()
//    ) { list ->
//        val builder = StringBuilder()
//        list.forEach {
//            builder.append("${it.id}\t${it.name}\t${it.age}\t${it.version2}")
//            builder.append("\n")
//        }
//        builder.toString()
//    }

    //通过传递的livedata里面的数据去获取另外一个livedata
//    val livedata : LiveData<List<String>> = Transformations.switchMap(userLiveData){
//        return@switchMap MutableLiveData<List<String>>()
//    }

    val deleteAll = View.OnClickListener {
        thread {
            database.getUserDao().deleteAll(database.getUserDao().getAll())
        }
        observableList.clear()
    }


    val insert = View.OnClickListener {
        thread {
            val list = mutableListOf<User>()
            for (i in 0..5) {
                val user = User(name = "name $i", age = i, version2 = "heihei $i")
                list.add(user)
            }
            database.getUserDao().insert(list)
        }
    }

//    val modify = View.OnClickListener {
//        thread {
//            database.getUserDao().insert()
//        }
//    }

    inner class OnRefreshAndLoadMore : OnRefreshLoadMoreListener {
        override fun onRefresh(refreshLayout: RefreshLayout) {
//            refresh()
            refreshLayout.finishRefresh(2000)
        }

        override fun onLoadMore(refreshLayout: RefreshLayout) {
            loadMore()
            refreshLayout.finishLoadMore(2000)
        }

    }
    var i = 1

    private fun loadMore() {
        i++
        thread {
            val list = mutableListOf<User>()
            for (m in (i - 10)..i) {
                var user = User(name = "name $m", age = m, version2 = "heihei $m")
                list.add(user)
//                observableList.add(RvItemViewModelDB(this,user))
            }
            database.getUserDao().insert(list)
        }
//        for (m in (i*5 + 1)..(i * 5 + 5)) {
//            var user = User(name = "name $m", age = m, version2 = "heihei $m")
//            observableList.add(RvItemViewModelDB(this,user))
//        }
    }

    val refreshAndLoadMore = OnRefreshAndLoadMore()

    val multipleItems = OnItemBindClass<Any>().apply {
        map<RvItemViewModelDB>(BR.viewModel, R.layout.rv_item_db)
//        map<String>(BR.item, R.layout.item)
    }




}